<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline='true'>
				<el-form-item>
					<el-input v-model="name" placeholder="团购项目"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getGoods">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="el-icon-plus" @click="handleAdd()"></el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="goods" highlight-current-row v-loading="listLoading" element-loading-text="拼命加载中" style="width: 100%;">
			<el-table-column type="expand">
				<template slot-scope="props">
					<el-form label-position="left" inline class="demo-table-expand">
						<el-form-item label="商品名称">
							<span>{{ props.row.goodsName }}</span>
						</el-form-item>
						<el-form-item label="供应商">
							<span>{{ props.row.supplierName }}</span>
						</el-form-item>
						<el-form-item label="团购城市">
							<span>{{ props.row.city }}</span>
						</el-form-item>
						<el-form-item label="商品库存">
							<span>{{ props.row.stock }}</span>
						</el-form-item>
						<el-form-item label="分类">
							<span>{{ props.row.category }}</span>
						</el-form-item>
						<el-form-item label="门店价格">
							<span>{{ props.row.storePrice }}</span>
						</el-form-item>
						<el-form-item label="团购价格">
							<span>{{ props.row.price }}</span>
						</el-form-item>
						<el-form-item label="最小团购成功人数">
							<span>{{ props.row.minimumPeople }}</span>
						</el-form-item>
						<el-form-item label="团购结束时间">
							<span>{{ props.row.endTime | dateformat('YYYY-MM-DD HH:mm:ss') }}</span>
						</el-form-item>
						<el-form-item label="描述">
							<span>{{ props.row.description }}</span>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>
			<el-table-column prop="id" label="ID" width="100">
			</el-table-column>
			<el-table-column prop="goodsName" label="商品名称" width="150">
			</el-table-column>
			<el-table-column prop="category" label="分类" width="120">
			</el-table-column>
			<el-table-column prop="price" label="团购价格" width="120">
			</el-table-column>
			<el-table-column prop="endTime" label="结束时间" :formatter="dateFormat" width="180">
			</el-table-column>
			<el-table-column prop="status" label="状态" width="100" :formatter="formatStatus">
			</el-table-column>
			<el-table-column label="操作" width="260">
				<template slot-scope="scope">
					<el-button type="warning" @click="">团购卷管理</el-button>
					<el-button type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)"></el-button>
					<el-button type="danger" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)"></el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination layout="total, prev, pager, next" @current-change="handleCurrentChange" :page-size="pagination.pageSize" :total="pagination.total" style="float:left;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="ID" prop="id">
					<el-input v-model="editForm.id" readonly></el-input>
				</el-form-item>
				<el-form-item label="商品名称">
					<el-input v-model="editForm.goodsName" prop="goodsName"></el-input>
				</el-form-item>
				<el-form-item label="团购城市">
					<el-select v-model="editForm.city" placeholder="请选择" @focus="handleSelectCity">
						<el-option
							v-for="item in cityOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="供应商">
					<el-select v-model="editForm.supplierName" placeholder="请选择" @focus="handleSelectSupplier">
						<el-option
							v-for="item in supplierOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="库存">
					<el-input v-model="editForm.stock"></el-input>
				</el-form-item>
				<el-form-item label="分类">
					<el-select v-model="editForm.category" placeholder="请选择" @focus="handleSelectCategory">
						<el-option
							v-for="item in categoryOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品图片" label-width="100px">
					<el-upload
						class="avatar-uploader"
						:action="baseUrl + '/goods/image'"
						:multiple="isMultiple"
						:show-file-list="false"
						:on-success="handleServiceAvatarScucess"
						:before-upload="beforeAvatarUpload">
						<img v-if="uploader.imgPath" :src="baseImgPath + uploader.imgPath" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="门店价格">
					<el-input v-model="editForm.storePrice"></el-input>
				</el-form-item>
				<el-form-item label="团购价格">
					<el-input v-model="editForm.price"></el-input>
				</el-form-item>
				<el-form-item label="最低团购成功人数">
					<el-input v-model="editForm.minimumPeople"></el-input>
				</el-form-item>
				<el-form-item label="结束时间">
					<div class="block">
						<el-date-picker
							v-model="editForm.endTime"
							type="datetime"
							placeholder="选择日期时间"
							default-time="00:00:00">
						</el-date-picker>
					</div>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="editForm.status" placeholder="请选择">
						<el-option
							v-for="item in statusOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="描述">
					<el-input v-model="editForm.description" type="textarea" :rows="2" ></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="商品名称">
					<el-input v-model="addForm.goodsName" prop="goodsName"></el-input>
				</el-form-item>
				<el-form-item label="团购城市">
					<el-select v-model="addForm.city" placeholder="请选择" @focus="handleSelectCity">
						<el-option
							v-for="item in cityOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="供应商">
					<el-select v-model="addForm.supplierName" placeholder="请选择" @focus="handleSelectSupplier">
						<el-option
							v-for="item in supplierOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="库存">
					<el-input v-model="addForm.stock"></el-input>
				</el-form-item>
				<el-form-item label="分类">
					<el-select v-model="addForm.category" placeholder="请选择" @focus="handleSelectCategory">
						<el-option
							v-for="item in categoryOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品图片" label-width="100px">
					<el-upload
						class="avatar-uploader"
						:action="baseUrl + '/goods/image'"
						:multiple="isMultiple"
						:show-file-list="false"
						:on-success="handleServiceAvatarScucess"
						:before-upload="beforeAvatarUpload">
						<img v-if="uploader.imgPath" :src="baseImgPath + uploader.imgPath" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="门店价格">
					<el-input v-model="addForm.storePrice"></el-input>
				</el-form-item>
				<el-form-item label="团购价格">
					<el-input v-model="addForm.price"></el-input>
				</el-form-item>
				<el-form-item label="最低团购成功人数">
					<el-input v-model="addForm.minimumPeople"></el-input>
				</el-form-item>
				<el-form-item label="结束时间">
					<div class="block">
						<el-date-picker
							v-model="addForm.endTime"
							type="datetime"
							placeholder="选择日期时间"
							default-time="00:00:00">
						</el-date-picker>
					</div>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="addForm.status" placeholder="请选择">
						<el-option
							v-for="item in statusOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="描述">
					<el-input v-model="addForm.description" type="textarea" :rows="2"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import { instance, getGoodsListPage, getSuppilerOptions, getCityOptions, getCategoryOptions, addGoods, updateGoods, removeGoods, getGoodsByName } from '../../api';
	let moment = require("moment"); // 直接在所需要的组件中引入

	export default {
		data() {
			return {
				goods: [],
				baseImgPath: 'http://localhost:8080',
				baseUrl: 'http://localhost:8080',
				isMultiple: true,
				name: '',
				edit: true,
				readonly: true,
				pagination: {
					total: 0,
					pageNum: 1,
					pageSize: 10,
				},
				uploader : {
					imgPath: '',
				},
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					goodsName: [
						{ required: true, message: '请输入商品名称', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: 0,
					goodsName: '',
					supplierName: '',
					category: '',
					city: '',
					stock: 0,
					storePrice: 0,
					price: 0,
					minimumPeople: 0,
					endTime: '',
					description: '',
					status: 0,
					imgPath: ''
				},

				supplierOptions: [],
				categoryOptions: [],
				cityOptions: [],

				statusOptions: [{
          value: 0,
          label: '团购中'
        }, {
          value: 1,
          label: '团购成功'
        }, {
					value: 2,
					label: '团购失败'
				}],

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					userId: [
						{ required: true, message: '请输入商品名称', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
					goodsName: '',
					supplierName: '',
					category: '',
					city: '',
					stock: 0,
					storePrice: 0,
					price: '445',
					minimumPeople: 0,
					endTime: '',
					description: '',
					status: 0,
					imgPath: ''
				},
			}
		},
		methods: {
			//状态显示转换
			formatStatus: function (row, column) {
				return row.status == 0 ? '团购中' : row.status == 1 ? '团购成功' : row.status == 2 ? '团购失败' : '未知';
			},
			dateFormat:function(row, column) {
        var date = row[column.property];
        if (date == undefined) {
          return "";
        }
        return moment(date).format("YYYY-MM-DD HH:mm:ss");
      },
			getSuppiler() {
				this.supplierOptions = [];
				getSuppilerOptions().then((res) => {
					const options = res.data.data.supplier;
					options.forEach((item,index) => {
						this.supplierOptions.push({
							label: item.supplierName,
							value: item.supplierName,
							index,
						})
					})
				});
			},
			handleSelectSupplier: function() {
				this.getSuppiler();
			},
			getCity() {
				this.cityOptions = [];
				getCityOptions().then((res) => {
					const options = res.data.data.city;
					options.forEach((item,index) => {
						this.cityOptions.push({
							label: item.cityName,
							value: item.cityName,
							index,
						})
					})
				});
			},
			handleSelectCity: function() {
				this.getCity();
			},
			getCategory() {
				this.categoryOptions = [];
				getCategoryOptions().then((res) => {
					const options = res.data.data.category;
					options.forEach((item,index) => {
						this.categoryOptions.push({
							label: item.category,
							value: item.category,
							index,
						})
					})
				});
			},
			handleSelectCategory: function() {
				this.getCategory();
			},
			handleCurrentChange(currentPage) {
				this.pagination.pageNum = currentPage;
				this.getUsers();
			},
			//图片上传
			handleServiceAvatarScucess(res, file) {
					if (res.code === 2000) {
							this.uploader.imgPath = res.data.imgPath;
					}else{
							this.$message.error('上传图片失败！');
					}
			},
			beforeAvatarUpload(file) {
					const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
					const isLt2M = file.size / 1024 / 1024 < 2;

					if (!isRightType) {
							this.$message.error('上传头像图片只能是 JPG 格式!');
					}
					if (!isLt2M) {
							this.$message.error('上传头像图片大小不能超过 2MB!');
					}
					return isRightType && isLt2M;
			},
			//获取商品列表
			getGoods() {
				let params = {
					name: this.name,
					currentPage: this.pagination.pageNum,
					pageSize: this.pagination.pageSize
				};
				console.log(params);
				this.listLoading = true;
				//NProgress.start();
				getGoodsByName(params).then((res) => {
					this.pagination.total = res.data.data.goods.total;
					this.goods = res.data.data.goods.list;
					this.listLoading = false;
					//NProgress.done();
				});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let params = { goodsId: row.id };
					removeGoods(params).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getGoods();
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
				this.uploader.imgPath = this.editForm.imgPath;
			},
			//显示新增界面
			handleAdd: function () {
				this.uploader.imgPath = '';
				this.addFormVisible = true;
				this.addForm = {
					goodsName: '',
					supplierName: '',
					category: '',
					city: '',
					stock: 0,
					storePrice: 0,
					price: 0,
					minimumPeople: 0,
					endTime: '',
					description: '',
					status: 0,
					imgPath: ''
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							this.editForm.imgPath = this.uploader.imgPath;
							let params = Object.assign({}, this.editForm);
							updateGoods(params).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getGoods();
							});
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							this.addForm.imgPath = this.uploader.imgPath;
							let params = Object.assign({}, this.addForm);
							addGoods(params).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getGoods();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let params = { ids: ids };
					batchRemoveUser(params).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getGoods();
		}
	}

</script>

<style scoped>
	.demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
	.avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
    }
    .avatar {
        width: 120px;
        height: 120px;
        display: block;
    }

</style>
